package cn.itcast.aspect;


import cn.itcast.mapper.OperateLogMapper;
import cn.itcast.pojo.OperateLog;
import cn.itcast.utils.CurrentHolder;
import cn.itcast.utils.TempMap;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class OperationLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    //@Around("execution(* cn.itcast.service.*Service.*(..))")
    @Around("@annotation(cn.itcast.aspect.LogOperation)")
    public Object method(ProceedingJoinPoint pjp) throws Throwable {
        //1.计算方法开始时间
        LocalDateTime start = LocalDateTime.now();
        System.out.println("====我是OperationLogAspect第一");
        Object result = pjp.proceed();
        LocalDateTime end = LocalDateTime.now();
        Duration between = Duration.between(start, end);

        long nanos = between.toNanos();

        //毫秒值
        long newTime = nanos / 1000000;

        //创建log日志对象
        OperateLog operateLog = new OperateLog();
        //操作时间
        operateLog.setOperateTime(LocalDateTime.now());
        //获取全类名
        operateLog.setClassName(pjp.getTarget().getClass().getName());
        //获取方法名字
        operateLog.setMethodName(pjp.getSignature().getName());
        //获取参数
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));

        //获取方法返回值
        operateLog.setReturnValue(result.toString());
        //获取方法执行时间
        operateLog.setCostTime(newTime);

        operateLog.setOperateEmpId((Integer) TempMap.get());


        //插入日志
        operateLogMapper.insert(operateLog);

        System.out.println("---------第四" + operateLog);


        return result;

    }
}
